package com.example.hello.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.hello.entity.Department;
import com.example.hello.mapper.DepartmentMapper;
import com.example.hello.service.DepartmentService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@RequiredArgsConstructor
public class DepartmentServiceImpl implements DepartmentService {
    
    private final DepartmentMapper departmentMapper;

    @Override
    public List<Department> listAll() {
        return departmentMapper.selectList(
            new LambdaQueryWrapper<Department>()
                .orderByDesc(Department::getUpdateTime)
        );
    }

    @Override
    public void add(String name) {
        // 检查名称是否已存在
        if (isDepartmentNameExists(name, null)) {
            throw new RuntimeException("部门名称已存在");
        }
        
        Department department = new Department();
        department.setDepartmentName(name);
        departmentMapper.insert(department);
    }

    @Override
    public void update(Integer id, String name) {
        // 检查部门是否存在
        Department existing = departmentMapper.selectById(id);
        if (existing == null) {
            throw new RuntimeException("部门不存在");
        }
        
        // 检查名称是否已存在（排除自身）
        if (isDepartmentNameExists(name, id)) {
            throw new RuntimeException("部门名称已存在");
        }

        Department department = new Department();
        department.setId(id);
        department.setDepartmentName(name);
        departmentMapper.updateById(department);
    }

    @Override
    public void delete(Integer id) {
        Department existing = departmentMapper.selectById(id);
        if (existing == null) {
            throw new RuntimeException("部门不存在");
        }
        departmentMapper.deleteById(id);
    }

    @Override
    public boolean approve(Integer id) {
        Department department = departmentMapper.selectById(id);
        if (department == null) {
            return false;
        }
        String name = department.getDepartmentName();
        return name != null && name.length() >= 3 && name.length() <= 10;
    }

    @Override
    public Department getById(Integer id) {
        return departmentMapper.selectById(id);
    }

    private boolean isDepartmentNameExists(String name, Integer excludeId) {
        LambdaQueryWrapper<Department> wrapper = new LambdaQueryWrapper<Department>()
            .eq(Department::getDepartmentName, name);
        
        if (excludeId != null) {
            wrapper.ne(Department::getId, excludeId);
        }
        
        return departmentMapper.selectCount(wrapper) > 0;
    }
} 